package socket.homework;
import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
/**
 * 聊天室客户端
 */
public class Client2 {
    private Socket socket;
    public Client2(){
        try {
            System.out.println("正在连接服务端...");
            socket = new Socket("localhost",8088); //三次握手
            System.out.println("服务端连接成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 该方法用于启动客户端程序的执行
     */
    public void start(){
        try {
            //启动线程用于读取来自服务端发送过来的消息
            ServerHandler handler = new ServerHandler();
            Thread t = new Thread(handler);
            t.start();

            //向服务端发送消息
            OutputStream out = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
            BufferedWriter bw = new BufferedWriter(osw);
            PrintWriter pw = new PrintWriter(bw,true); //自动行刷新

            Scanner scan = new Scanner(System.in);
            while(true){
                System.out.println("请输入昵称:");
                String nickName = scan.nextLine();
                if(nickName.trim().isEmpty()){
                    System.out.println("昵称不能为空");
                }else{
                    pw.println(nickName); //将昵称发送给服务端
                    break;
                }
            }

            while(true){
                String line = scan.nextLine();
                if("exit".equalsIgnoreCase(line)){
                    break;
                }
                pw.println(line); //发送到服务端
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close(); //四次挥手
            } catch (IOException e) {
            }
        }
    }

    public static void main(String[] args) {
        Client2 client = new Client2();
        client.start();
    }

    /**
     * 该线程用于接收服务端发送过来的消息
     */
    private class ServerHandler implements Runnable{
        public void run(){
            try {
                //通过socket获取输入流用于读取服务端发送过来的消息
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in,StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);

                String message;
                while((message=br.readLine())!=null){
                    System.out.println(message); //将服务端发送过来的消息输出
                }
            } catch (IOException e) {
            }
        }
    }
}